Ext.define('appmod.controller.resources.Menu', {
    extend: 'Ext.app.Controller',

    views: [
    	'resources.MenuResForm',
		'resources.MenuHierarchy',
		'resources.AllMenuTreeGrid'
    ],
	
	models : [
		'resources.AllMenuTreeModel'
	],
	
    stores: [
		'resources.RegisterModuleSelStore',
		'resources.AllMenuTreeStore'
	],	

    refs: [
		{ref: 'menuhieraTreePanel',selector:'menuhierarchypanel > allmenutreegrid'},
		{ref: 'menuhieraPanel',selector:'menuhierarchypanel'}
	],

    init: function() {

    	this.control({
			
			'menuhierarchypanel  button[action=save]': {
				click:this.menuhierChangeSave
			},
			
			'menuhierarchypanel button[action=addnewmenu]': {
				click:this.addNewMenu
			},

			'menuhierarchypanel button[action=removemenu]': {
				click:this.removeMenu
			},
			
			'menuhierarchypanel button[action=reflesh]' : {
				click:this.refleshMenu
			},
			
			'menuresourceform button[action=selectParentMenu]' : {
				click:this.selectParentMenu
			},
			
			'menuresourceform button[action=clearParentMenu]' : {
				click:this.clearParentMenu
			},
			
			'menuresourceform button[action=save]': {
				click:this.saveNewMenu
			},
						
			'menuresourceform button[action=reset]': {
				click:this.resetMenuForm
			}			
						


    	});

    },
	
	
	menuhierChangeSave:function() {
		
		me = this;

		var menuhieraPanel = me.getMenuhieraPanel();
		var menuhieraTreePanel = me.getMenuhieraTreePanel();

		var store = menuhieraTreePanel.getStore();
		var updatedRecords = store.getUpdatedRecords();
		
		var jsonData = [];
		
		// --- get update record s ---
		for (var i =0 ; i < updatedRecords.length ; i++) {
			var record = updatedRecords[i];
			
			var node = store.getNodeById(record.getId() );
			var updateItem = {
				method : 'update',
				id : record.getId(),
				code : record.get('code'),
				parentId : node.parentNode.getId()
			}
			jsonData.push( updateItem );
		}
		
		// --- remove record ---
		var removedRecords = store.getRemovedRecords();
		for (var i =0 ; i < removedRecords.length ; i++) {
			var record = removedRecords[i];
			var removeItem = {
				method : 'delete',
				id : record.getId()
			}
			jsonData.push( removeItem );
			
		}
		
		/// --- using ajax ---
		// --- update record using ajax
		try {

			Ext.Ajax.request({
				url: '../../data/resource/resources/mergeAllMenu.json',
				method:'post',
				params:{
					'jsonData':Ext.encode(jsonData)
				},
				success: function(response, opts) {
					 
					 var obj = Ext.decode(response.responseText);
					 
					 // --- popup message ---
					Ext.MessageBox.show({
        				title: "提示",
        				msg: obj.msg,
        				buttons: Ext.MessageBox.OK,
        				icon: Ext.MessageBox.WARNING
       				});
					
					// --- reload ---
					

				},
				failure: function(response, opts) {
				
				}
			});

			
		} catch (e) {
			alert(e);
		}		
		
		
	},
	
	loadInitComp : function() {
		
		var mainPanel =	Ext.create('Ext.tab.Panel', {
                    activeTab:0,
                    region:'center',
                    plain: true,
                    items:[
                        {
							xtype:'menuhierarchypanel',
							title:'菜单组织结构'
						},
                        Ext.create('appmod.view.resources.MenuDashboard'),
						Ext.create('appmod.view.resources.MenuRegDashboard')
                    ]
              
            
    	});	
		return mainPanel;		
	},
	
	refleshMenu :function() {
		var me = this;
		var menuhieraPanel = me.getMenuhieraTreePanel();
		var store = menuhieraPanel.getStore();
		store.load();
	},
	
	// --- private variable ---
	
	// --- add new menu ---
	addNewMenu:function() {
		
		var me = this;

		// --- whether select menu   ---
		var menuhieraPanel = me.getMenuhieraTreePanel();
		var selectionModel = menuhieraPanel.getSelectionModel();
		var records = selectionModel.getSelection();
		
		
		// --- build new form ---
		if (!this.winForMenuForm) {
			this.winForMenuForm = new Ext.create('widget.window', {
				title : '菜单资料',
				closable : true,
				closeAction:'hide',
				width : 500,
				height : 300,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					id : 'menuresourceform',
					xtype : 'menuresourceform',
					url:'../../data/resource/resources/submitmenuform.json',
					region:'center'
				}]

			});
		}
		
		if (records.length > 0) {
			// --- init object --- 
			var initValue = {
				parentName : records[0].get('text'),
				parentId: records[0].get('id')
			}
			var form = Ext.getCmp('menuresourceform');

			form.getForm().setValues(initValue);			
		}
		
		if ( this.winForMenuForm.isVisible() ) {
			
		} else {
			this.winForMenuForm.show();
		}
	},
	
	resetMenuForm : function() {
		var form = Ext.getCmp('menuresourceform');

		form.getForm().reset();
					
	},
	
	removeMenu : function() {
		
		me = this;
		
		var menuhiPanel = me.getMenuhieraTreePanel();
		
		var menuhieraPanel = me.getMenuhieraPanel();
		
		var records = menuhiPanel.getView().getChecked();

		for (var i = records.length -1  ; i >= 0 ; i--) {
			// --- record ---
			 records[i].remove();
			 menuhieraPanel.getChangedRecord().add( records[i].getId() , 'delete' );
		}


	},
	
	
	
	saveNewMenu:function() {
		
		var me = this;

		var formPanel = Ext.getCmp('menuresourceform');
		var form = formPanel.getForm();
		
		if ( form.isValid() ) {

			// --- submit form 
			form.submit({
				success:function(form, action) {
					Ext.Msg.alert('成功', action.result.msg);
					if ( me.winForMenuForm.isVisible() ) {
						me.winForMenuForm.hide();			
					}
					// --- clear all value ---
					form.setValues({
						parentName : '',
						code:'',
						idSysRes:'',
						name:'',
						moduleId:'',
						parentId:''						
					});

				},
				failure:function(form, action) {
					Ext.Msg.alert('失败', action.result.msg); 
				}
			});
			
		}
		

	},
	
	selectParentMenu:function() {
		
		me = this;
		
		// --- build new form ---
		if (!this.winForMenuTree) {
			this.winForMenuTree = new Ext.create('widget.window', {
				title : '菜单结构图',
				closable : true,
				closeAction:'hide',
				width : 500,
				height : 400,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					id:'allmenutreegrid',
					xtype : 'allmenutreegrid',
        			useArrows: true,
					multiSelect: false,
        			rootVisible: false,					
					store: Ext.create('appmod.store.resources.AllMenuTreeStore'),
					region:'center'
				}],
				dockedItems: [{
            		xtype: 'toolbar',
            		dock: 'bottom',
            		ui: 'footer',
            		layout: {
                		pack: 'end'
            		},
            		items: [{
                		minWidth: 80,
                		text: '选择关闭',
						scope : me,
						handler : me.selectAndCloseParentWindow
            		}]
	        	}]
			});
		}
		
		if ( this.winForMenuTree.isVisible() ) {
			
		} else {
			this.winForMenuTree.show();
		}		
		
	},
	
	selectAndCloseParentWindow : function() {
		var treeGrid = Ext.getCmp('allmenutreegrid');
		var selMod = treeGrid.getSelectionModel();
		var records = selMod.getSelection();
		
		
		var form = Ext.getCmp('menuresourceform');
		var textfieldssels = form.query("textfield[name=parentName]");
		var idsParentSelected = form.query("hiddenfield[name=parentId]");
		

		textfieldssels[0].setValue( records[0].get('text') );
		idsParentSelected[0].setValue( records[0].id );

		
		if ( this.winForMenuTree.isVisible() ) {
			this.winForMenuTree.hide();
		} 		
		
	},
	
	clearParentMenu:function() {
		
		var form = Ext.getCmp('menuresourceform');
		var textfieldssels = form.query("textfield[name=parentName]");
		var idsParentSelected = form.query("hiddenfield[name=parentId]");
		
		textfieldssels[0].setValue('' );
		idsParentSelected[0].setValue( '');
				
		

	}
	
});